import router from "@/router";
import axios from "axios";
import {
    Message
} from "element-ui";
import QS from "qs"
let baseurl = "/api/"



// 设置请求拦截
axios.interceptors.request.use((req) => {
    req.headers.authorization = JSON.parse(sessionStorage.getItem('admininfo') || "{}").token;
    return req
})



// 响应拦截器
axios.interceptors.response.use((res) => {
    // console.log(res);
    if (res.data.code == 403) {
        // 提升错误信息
        Message.error(res.data.msg)
        setTimeout(() => {
            router.push("/login")
        }, 500);
    }
    return res.data
})

// get
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        axios.get(baseurl + url, {
            params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

// post
export const post = (url, params = {},File=false) => {
    let data = null
   
    if (File) { //如果有文件上传
        data = new FormData()
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        //普通
        data = QS.stringify(params) //对象转字符串
        // Content-Type: application/json
        // Content-Type: application/x-www-form-urlencoded
    }
    return new Promise((resolve, reject) => {
        axios.post(baseurl + url, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}